{extend name="base"/}
{block name="resources"}
<style>
    /* 提示弹出框 */
    .card-common:first-of-type{margin-top: 0;}
    .layui-card-body{display: flex;padding-bottom: 0 !important;padding-right: 50px !important;padding-left: 50px !important;flex-wrap: wrap;}
    .layui-card-body .content{width: 33.3%;display: flex;flex-direction: column;margin-bottom: 30px;justify-content: center;}
    .layui-card-body .content .title{color: #909399;font-size: 14px;}
    .layui-card-body .money{color: #303133;font-size: 26px;margin-top: 10px;max-width: 250px;}
    .layui-card-body .bottom-title{color: #909399;font-size: 14px;margin-top: 5px;}
    .table-bottom .layui-table-page {position: inherit;text-align: right}
    .table-tab .layui-tab-content{margin-bottom: 0;}
    .screen {margin-top: 15px}
    .table-title {cursor: pointer}
    .layui-layout-admin.admin-style-2 .table-tab .layui-tab-title {margin-bottom: 15px;}
    .layui-layout-admin.admin-style-2 .layui-form-item .layui-input-inline{background-color: #fff;}
</style>
{/block}

{block name="main"}
<div class="layui-card card-common card-brief">
    <div class="layui-card-header">
        <div>
            <span class="card-title">优惠券概况</span>
        </div>
    </div>
    <div class="layui-card-body">
        <div class="content">
            <p class="title">累计发放</p>
            <p class="money">{$total_count}</p>
        </div>
        <div class="content">
            <p class="title">已使用</p>
            <p class="money">{$used_count}</p>
        </div>
        <div class="content">
            <p class="title">待使用</p>
            <p class="money">{$not_used_count}</p>
        </div>
    </div>
</div>

<div class="screen layui-collapse" lay-filter="selection_panel">
    <div class="layui-colla-item">
        <form class="layui-colla-content layui-form layui-show">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">昵称/手机号：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="search_text" placeholder="请输入会员昵称/手机号" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">获取方式：</label>
                    <div class="layui-input-inline">
                        <select name="get_type">
                            <option value="">全部</option>
                            {foreach $get_type as $k => $val}
                            <option value="{$k}">{$val}</option>
                            {/foreach}
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">领取时间：</label>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" name="start_time" placeholder="开始时间" id="start_time" readonly>
                        <i class=" iconrili iconfont calendar"></i>
                    </div>
                    <div class="layui-form-mid">-</div>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" name="end_time" placeholder="结束时间" id="end_time" readonly>
                        <i class=" iconrili iconfont calendar"></i>
                    </div>
                    <button class="layui-btn layui-btn-primary date-picker-btn date-picker-btn-seven" onclick="datePick(7, this);return false;">近7天</button>
                    <button class="layui-btn layui-btn-primary date-picker-btn date-picker-btn-thirty" onclick="datePick(30, this);return false;">近30天</button>
                </div>
            </div>
            <div class="form-row">
                <button class="layui-btn" lay-submit="" id="search" lay-filter="search">筛选</button>
            </div>
        </form>
    </div>
</div>

<div class="layui-tab table-tab" lay-filter="coupon_tab">
    <ul class="layui-tab-title">
        <li class="layui-this" lay-id="">全部</li>
        <li lay-id="1">已领取</li>
        <li lay-id="2">已使用</li>
        <li lay-id="3">已过期</li>
    </ul>
    <div class="layui-tab-content">
        <!-- 列表 -->
        <table id="coupon" lay-filter="coupon"></table>
    </div>
</div>
{/block}

{block name="script"}
<script type="text/html" id="memberInfo">
    <div class='table-title'>
        <div class='title-pic'>
            <img layer-src src="{{ns.img(d.headimg)}}" onerror="this.src = '{:img('public/static/img/default_img/head.png')}' ">
        </div>
        <div class='title-content' onclick="location.href = ns.url('shop/member/editmember?member_id={{d.member_id}}')">
            <p class="layui-elip">{{d.nickname}}</p>
            <p class="layui-elip">{{d.mobile}}</p>
        </div>
    </div>
</script>

<script type="text/html" id="operation">
    <div class="table-btn" align="right">
        {{# if(d.state == 1){ }}
        <a class="layui-btn" lay-event="recovery">回收</a>
        {{# } }}
    </div>
</script>

<script type="text/html" id="toolbarOperation">
    <button class="layui-btn layui-btn-primary" lay-event="recovery">批量回收</button>
</script>

<script type="text/html" id="batchOperation">
    <button class="layui-btn layui-btn-primary" lay-event="recovery">批量回收</button>
</script>

<script>
    var form, laydate, element, getType = {:json_encode($get_type)};
    layui.use(['laydate','form', 'element'], function(){
        form = layui.form;
        laydate = layui.laydate;
        element = layui.element;

        element.on('tab(coupon_tab)', function(){
            table.reload({
                page: {curr: 1},
                where: {'state': this.getAttribute('lay-id')},
            })
        });

        form.on('submit(search)', function(data) {
            if ($('#start_time').val() != '' && $('#end_time').val() != '' && (new Date($('#end_time').val()).getTime() <= new Date($('#start_time').val()).getTime() )) {
                layer.msg('结束时间不能小于开始时间');
                return false;
            }
            data.field.state = this.getAttribute('lay-id');

            table.reload({
                page: {
                    curr: 1
                },
                where: data.field
            });
            return false;
        });

        laydate.render({
            elem: '#start_time',
            type: 'datetime',
            max: 0,
            change: function(value, date, endDate){
                $(".date-picker-btn").removeClass("selected");
            }
        });
        laydate.render({
            elem: '#end_time',
            type: 'datetime',
            max: 0,
            change: function(value, date, endDate){
                $(".date-picker-btn").removeClass("selected");
            }
        });

        table = new Table({
            elem: '#coupon',
            url: ns.url("shop/memberaccount/coupon"),
            cols: [
                [{
                    type: 'checkbox',
                    width: '3%',
                    unresize: 'false'
                },{
                    templet: '#memberInfo',
                    title: '会员信息',
                    width: '20%',
                    unresize: 'false'
                }, {
                    field: 'coupon_name',
                    title: '优惠券',
                    width: '10%',
                    unresize: 'false',
                    templet: function(data) {
                        return `<a href="`+ ns.url('coupon://shop/coupon/detail', {coupon_type_id: data.coupon_type_id }) +`" target="_blank" class="text-color">`+ data.coupon_name +`</a>`;
                    }
                }, {
                    title: '类型',
                    width: '10%',
                    unresize: 'false',
                    templet: function (data) {
                        return data.type == 'reward' ? '满减券' : '折扣券';
                    }
                }, {
                    title: '获取方式',
                    width: '10%',
                    unresize: 'false',
                    templet: function(data) {
                        return getType[data.get_type] ? getType[data.get_type] : '';
                    }
                }, {
                    title: '状态',
                    width: '12%',
                    unresize: 'false',
                    templet: function (data) {
                        var str = '';
                        switch (data.state) {
                            case 1:
                                str = '已领取';
                                break;
                            case 2:
                                str = '已使用';
                                break;
                            case 3:
                                str = '已过期';
                                break;
                        }
                        return str;
                    }
                },  {
                    title: '领取时间',
                    width: '15%',
                    unresize: 'false',
                    templet: function(data) {
                        return ns.time_to_date(data.fetch_time);
                    }
                }, {
                    title: '使用时间',
                    width: '15%',
                    templet: function(data) {
                        return data.use_time ? ns.time_to_date(data.use_time) : '';
                    }
                },
                {
                    title: '操作',
                    width: '5%',
                    templet: '#operation'
                }
                ]
            ],
            parseData: function(data){
                data.data.list = data.data.list.map(function (item) {
                    item.LAY_DISABLED = item.state != 1;
                    return item;
                })
                return {
                    "code": data.code,
                    "msg": data.message,
                    "count": data.data.count,
                    "data": data.data.list
                };
            },
            toolbar: '#toolbarOperation',
            bottomToolbar: "#batchOperation"
        });

        table.tool(function(obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'recovery': //编辑
                    recoveryCoupon([{coupon_type_id: data.coupon_type_id, coupon_id: data.coupon_id}]);
                    break;
            }
        })

        /**
         * 批量操作
         */
        table.bottomToolbar(function(obj) {
            if (obj.data.length < 1) {
                layer.msg('请选择要操作的数据');
                return;
            }
            switch (obj.event) {
                case "recovery":
                    var id_array = new Array();
                    for (i in obj.data) id_array.push({coupon_type_id: obj.data[i].coupon_type_id, coupon_id: obj.data[i].coupon_id});
                    recoveryCoupon(id_array);
                    break;
            }
        });

        /**
         * 批量操作
         */
        table.toolbar(function(obj) {
            if (obj.data.length < 1) {
                layer.msg('请选择要操作的数据');
                return;
            }
            switch (obj.event) {
                case "recovery":
                    var id_array = new Array();
                    for (i in obj.data) id_array.push({coupon_type_id: obj.data[i].coupon_type_id, coupon_id: obj.data[i].coupon_id});
                    recoveryCoupon(id_array);
                    break;
            }
        });
    });

    function recoveryCoupon(data) {
        layer.confirm('回收将会收回会员领取的待使用的优惠券，已使用的将无法回收，确定要回收所选优惠券吗？', function() {
            $.ajax({
                url: ns.url("coupon://shop/coupon/recoverycoupon"),
                data: {
                    coupon_list: JSON.stringify(data)
                },
                dataType: 'JSON',
                type: 'POST',
                success: function(res) {
                    layer.msg(res.message);
                    if (res.code == 0) {
                        table.reload();
                    }
                }
            });
        })
    }

    /**
     * 七天时间
     */
    function datePick(date_num,event_obj){
        $(".date-picker-btn").removeClass("selected");
        $(event_obj).addClass('selected');
        // alert(new Date().format("yyyy-MM-dd hh:mm"));
        var now_date = new Date();

        Date.prototype.Format = function (fmt,date_num) { //author: meizz
            this.setDate(this.getDate()-date_num);
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "H+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        };
        // var now_time =  new Date().Format("yyyy-MM-dd HH:mm:ss",0);//当前日期
        var now_time =  new Date().Format("yyyy-MM-dd 23:59:59",0);//当前日期
        var before_time =  new Date().Format("yyyy-MM-dd 00:00:00",date_num-1);//前几天日期
        $("input[name=start_time]").val(before_time,0);
        $("input[name=end_time]").val(now_time,date_num-1);
    }
</script>
{/block}